package com.example.wiki.service.impl;

import com.example.wiki.common.util.CopyUtil;
import com.example.wiki.req.EbookQueryReq;
import com.example.wiki.req.EbookSaveReq;
import com.example.wiki.util.SnowFlake;
import com.example.wiki.vo.EbookVo;
import com.example.wiki.common.vo.PageVo;
import com.example.wiki.entity.Ebook;
import com.example.wiki.entity.EbookExample;
import com.example.wiki.mapper.EbookMapper;
import com.example.wiki.service.EbookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class EbookServiceImpl implements EbookService {

    @Autowired
    EbookMapper ebookMapper;

    @Autowired
    SnowFlake snowFlake;//使用雪花算法生成id

    @Override
    public  PageVo<EbookVo> list(EbookQueryReq ebookQueryReq) {
        //组装sql
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(! ObjectUtils.isEmpty(ebookQueryReq.getName()) )
        criteria.andNameLike("%" + ebookQueryReq.getName() +"%");
        if(! ObjectUtils.isEmpty(ebookQueryReq.getCategory2Id()) )
            criteria.andCategory2IdEqualTo(ebookQueryReq.getCategory2Id());

        //分页查询
        PageHelper.startPage(ebookQueryReq.getPage(), ebookQueryReq.getSize());
        List<Ebook> list = ebookMapper.selectByExample(ebookExample);

        //处理数据后封装
        PageInfo<Ebook> pageInfo = new PageInfo<>(list);
        List<EbookVo> ebookVoList = CopyUtil.copyList(list, EbookVo.class);
        PageVo<EbookVo> pageVo =new PageVo<EbookVo>();
        pageVo.setList(ebookVoList);
        pageVo.setTotal(pageInfo.getTotal());
        return pageVo;
    }

    @Override
    public void save(EbookSaveReq ebookSaveReq) {
        Ebook ebook =CopyUtil.copy(ebookSaveReq,Ebook.class);
        System.out.println(ebook);
        if(ObjectUtils.isEmpty(ebook.getId())){
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }else{
            ebookMapper.updateByPrimaryKeySelective(ebook);
        }
    }

    @Override
    public void remove(Long id) {
        if (id != null){
            ebookMapper.deleteByPrimaryKey(id);
        }
    }
}
